#include "head.h"

int readConf(const char* conf,char* ip,char* port,char* threadNum)
{   
    int fd = open(conf,O_RDONLY);
    ERROR_CHECK(fd,-1,"open");

    char tmp[1024] = {0};
    read(fd,tmp,sizeof(tmp));

    char* ptmp = strtok(tmp,"\n");
    strcpy(ip,ptmp);
    printf("%s\n",ip);
    ptmp = strtok(NULL,"\n");
    strcpy(port,ptmp);
    printf("%s\n",port);
    ptmp = strtok(NULL,"\n");
    strcpy(threadNum,ptmp);
    printf("%s\n",threadNum);

    return 0;
}

int recvOrder(int netfd,int* orderflag,char* args)
{
    int length;
    char buf[1000]={0};
    recv(netfd,&length,sizeof(int),MSG_WAITALL);
    recv(netfd,buf,length,MSG_WAITALL);
    sscanf(buf,"%d%s",orderflag,args);
    return 0;
}

int user_Register(int netfd,MYSQL* mysql)
{
    int length;
    char username[256] = {0};
    char userpasswd[256] = {0}; 
    recv(netfd,&length,sizeof(int),MSG_WAITALL);
    recv(netfd,username,length,MSG_WAITALL);

    recv(netfd,&length,sizeof(int),MSG_WAITALL);
    recv(netfd,userpasswd,length,MSG_WAITALL);

    char salt[13] = {0};
    generateSalt(salt);
    printf("salt = %s\n",salt);

    char* encryptedPasswd =  crypt(userpasswd,salt);

    char sql[1024] = {0};
    sprintf(sql,"insert into user_table (username,salt,crypted_passwd) values('%s','%s','%s');",username,salt,encryptedPasswd);
    int qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"insert into user_table error :%s\n", mysql_error(mysql));
        send(netfd,"1",1,MSG_NOSIGNAL);//有重复
        return -1;
    }
    send(netfd,"0",1,MSG_NOSIGNAL);//是否成功

    char path[256] = {0};
    sprintf(path,"%s/%s","netdisk",username);
    bzero(sql,sizeof(sql));
    sprintf(sql,"insert into file_system (filename,username,parentId,type,path,isDelete) values('%s','%s','%d','%s','%s','%d');",
            username,username,-1,"d",path,0);

    qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"insert into file_system error :%s\n", mysql_error(mysql));
        return -1;
    }

    bzero(sql,sizeof(sql));
    sprintf(sql,"select id from file_system where username = '%s';",username);
    qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"select id from file_system error :%s\n", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(res);
    int id = atoi(row[0]);
    printf("id = %d\n",id);

    return id;
}

int checkLogin(int sockfd,MYSQL* mysql)
{
    int length;
    char username[256] = {0};
    char userpasswd[256] = {0}; 
    recv(sockfd,&length,sizeof(int),MSG_WAITALL);
    recv(sockfd,username,length,MSG_WAITALL);

    recv(sockfd,&length,sizeof(int),MSG_WAITALL);
    recv(sockfd,userpasswd,length,MSG_WAITALL);

    printf("username = %s\n",username);
    printf("userpasswd = %s\n",userpasswd);

    char sql[1024] = {0};
    sprintf(sql,"select salt from user_table where username = '%s';",username);
    int qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"select crypted_passwd from user_table error :%s\n", mysql_error(mysql));
    }
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(res);
    char salt[32] = {0};
    strcpy(salt,row[0]);
    char* encryptedPasswd =  crypt(userpasswd,salt);
    printf("passwd = %s\n",encryptedPasswd);

    bzero(sql,sizeof(sql));
    sprintf(sql,"select crypted_passwd from user_table where username = '%s';",username);
    qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"select crypted_passwd from user_table error :%s\n", mysql_error(mysql));
    }
    res = mysql_store_result(mysql);
    row = mysql_fetch_row(res);
    if(strcmp(row[0],encryptedPasswd) == 0)
    {
        printf("Login!\n");
        send(sockfd,"1",sizeof(char),MSG_NOSIGNAL);
    }
    else
    {
        printf("Can not login!\n");
        send(sockfd,"2",sizeof(char),MSG_NOSIGNAL);
        return -1;
    }

    bzero(sql,sizeof(sql));
    sprintf(sql,"select id from file_system where username = '%s';",username);
    qret = mysql_query(mysql,sql);
    if(qret != 0)
    {
        fprintf(stderr,"select id from file_system error :%s\n", mysql_error(mysql));
        return -1;
    }
    res = mysql_store_result(mysql);
    row = mysql_fetch_row(res);
    int id = atoi(row[0]);
    printf("id = %d\n",id);

    return id;
}

int generateSalt(char* str)
{
    int i,flag;
    str[0] = '$';
    str[1] = '6';
    str[2] = '$';
    srand(time(NULL));
    for(i = 3; i < 12; ++i)
    {
        flag = rand()%3;
        switch(flag)
        {
        case 0:
            str[i] = rand()%26 + 'a';
            break;
        case 1:
            str[i] = rand()%26 + 'A';
            break;
        case 2:
            str[i] = rand()%10 + '0';
            break;
        }
        if(i == 11)
        {
            str[i] = '$';
        }
    }
    //printf("%s\n", str);

    return 0;
}

int sendLs(int netfd,int cdcode,MYSQL*mysql)
{
    MYSQL *cur=mysql;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char username[257]={0};
    char sql[1024]={0};
    sprintf(sql,"select username from file_system where id='%d'",cdcode);
    int qret=mysql_query(cur,sql);
    if(qret!=0)
    {
        fprintf(stderr,"SQL statesment error:%s\n",mysql_error(cur));

    }
    res=mysql_store_result(cur);
    row=mysql_fetch_row(res);
    sprintf(username,"%s",row[0]);
    printf("name=%s\n",username);
    sprintf(sql,"select filename from file_system where username='%s'and isDelete=0 and parentId='%d'",username,cdcode);  
    qret=mysql_query(cur,sql);
    if(qret!=0)
    {
        fprintf(stderr,"SQL statesment error:%s\n",mysql_error(cur));
    }
    res=mysql_store_result(cur);
    while((row=mysql_fetch_row(res))!=NULL)
    {
        int length;
        printf("i am row here\n");
        char buff[1024];
        memset(buff,0,sizeof(buff));
        length=strlen(row[0]);
        send(netfd,&length,sizeof(int),MSG_NOSIGNAL);
        strcpy(buff,row[0]);
        send(netfd,buff,length,MSG_NOSIGNAL);
    }
    int num=0;
    send(netfd,&num,sizeof(int),MSG_NOSIGNAL);
    return 0;
}

int sendPwd(int netfd,int cdcode,MYSQL*mysql)
{
    MYSQL *cur=mysql;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char sql[1024]={0};
    sprintf(sql,"select path from file_system where id='%d';",cdcode);
    int ret= mysql_query(mysql,sql);    
    if(ret!=0)
    {
        fprintf(stderr,"mysql connect error:%s\n",mysql_error(mysql));
    }
    res=mysql_store_result(mysql);
    char buff[1024]={0};
    row=mysql_fetch_row(res);
    sprintf(buff,"%s",row[0]);
    printf("buff=%s\n",buff);
    int length=strlen(row[0]);
    send(netfd,&length,sizeof(int),MSG_NOSIGNAL);
    send(netfd,buff,length,MSG_NOSIGNAL);
    return 0;
}

int removefile(int cdcode,char *args,MYSQL*mysql)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char sql[1024]={0};
    sprintf(sql,"select *from file_system where parentId='%d';",cdcode);
    int ret=mysql_query(mysql,sql);
    if(ret!=0)
    {
        fprintf(stderr,"mysql connect error:%s\n",mysql_error(mysql));
    }
    res=mysql_store_result(mysql);
    while((row=mysql_fetch_row(res))!=NULL)
    {
        printf("buf=%s\n",row[1]);
        if (strcmp(row[1],args)==0)
        {
            memset(sql,0,sizeof(sql));
            sprintf(sql,"update file_system set isDelete=1 where parentId='%d'and filename='%s';",cdcode,args);
            ret=mysql_query(mysql,sql);
            if(ret!=0)
            {
                fprintf(stderr,"mysql connect error:%s\n",mysql_error(mysql));
            }
            return 0;
        }
    }
    return -1;
} 

int createMkdir(int cdcode,char *args,MYSQL*mysql)
{
    MYSQL_RES *res;
    MYSQL_ROW row;
    char username[256]={0};
    char oldpath[1024]={0};
    char newpath[1024]={0};
    char sql[1024]={0};
    sprintf(sql,"select path,username from file_system where id='%d';",cdcode);
    int ret=mysql_query(mysql,sql);
    if(ret!=0)
    {
        fprintf(stderr,"mysql connect error:%s\n",mysql_error(mysql));
    }
    res=mysql_store_result(mysql);
    row=mysql_fetch_row(res);
    sprintf(username,"%s",row[1]);
    printf("username=%s\n",username);
    sprintf(oldpath,"%s",row[0]);
    printf("oldpath=%s\n",oldpath);
    sprintf(newpath,"%s/%s",oldpath,args);
    printf("newpath=%s\n",newpath);
    memset(sql,0,sizeof(sql));
    sprintf(sql,"insert into file_system(filename,username,parentId,type,path,isDelete)values('%s','%s','%d','d','%s',0);",args,username,cdcode,newpath);
    ret=mysql_query(mysql,sql);
    if(ret!=0)
    {
        fprintf(stderr,"mysql connect error:%s\n",mysql_error(mysql));
    }
    return 0;
}

int myCd(int netfd, int id, char* args, MYSQL* mysql)
{


    printf("args:%s\n",args);
    int parentId;
    char tmpPath[256];
    //根据id将当前工作路径取出
    char sql[1024];
    bzero(sql,sizeof(sql));
    bzero(tmpPath,sizeof(tmpPath));
    sprintf(sql,"select * from file_system where id = %d",id);
    int qret = mysql_query(mysql,sql);
    if(qret != 0){
        fprintf(stderr,"SQL statement error: %s\n",mysql_error(mysql));
    }
    MYSQL_RES* res = mysql_store_result(mysql);
    MYSQL_ROW row = mysql_fetch_row(res);
    if(row ==  NULL){
        printf("curWorking-row == 0?\n");
    }
    sprintf(tmpPath,"%s",row[5]);
    printf("tmpPath:%s\n",tmpPath);


    char* substr = NULL;;
    substr = strtok(args,"/");
    printf("%s %lu\n,",substr,strlen(substr));
    if(substr == NULL){ //截取子串，cd不给参数i，回到更目录
        //往回走，直到parentId == -1
        parentId = atoi(row[3]);
        while(parentId != -1){
            sprintf(sql,"select * from file_system where id = %d",parentId);
            qret = mysql_query(mysql,sql);
            if(qret != 0){
                fprintf(stderr,"SQL statement error: %s\n",mysql_error(mysql));        
            } 
            res = mysql_store_result(mysql);
            row = mysql_fetch_row(res);
            parentId = atoi(row[3]);
        }
        //此时，已经返回到根目录
        //printf("%s\n",row[5]);
        id = atoi(row[0]);
        return id;
    }
    while(substr != NULL){
        if(strcmp(substr,".") == 0){
            //not toto
        }else if(strcmp(substr,"..") == 0){
            //得到当前行路径的parentID
            sprintf(sql,"select * from file_system where id = %d;",id);
            qret = mysql_query(mysql,sql);
            if(qret != 0){
                fprintf(stderr,"SQL statement error: %s\n",mysql_error(mysql));        
            }
            res = mysql_store_result(mysql);
            row = mysql_fetch_row(res);
            //printf("luguo: %s\n",row[5]);
            parentId = atoi(row[3]);
            if(parentId != -1){
                id = parentId;
                //消除末尾的路劲子串
                int len = strlen(tmpPath) - 1;
                while(len >= 0 && tmpPath[len] != '/'){
                    //  printf("%c ",tmpPath[len]);
                    tmpPath[len] = '\0';
                    len--;
                }
                tmpPath[len] = '\0';
                //printf("%c\n",tmpPath[len]);
            }
            //id = parentId;

            printf("..later ——> %s\n",tmpPath);
        }
        else{
            //往下走
            //当前工作目录和子串进行拼接，查文件表，判断是否存在
            sprintf(tmpPath,"%s/%s",tmpPath,substr);
            //printf("tmpPath/substr: --> %s\n",tmpPath);
            sprintf(sql,"select * from file_system where path = '%s'",tmpPath);
            qret = mysql_query(mysql,sql);
            if(qret != 0){
                fprintf(stderr,"SQL statement error: %s\n",mysql_error(mysql));        
            }
            res = mysql_store_result(mysql);
            row = mysql_fetch_row(res);
            int rows = mysql_num_rows(res);
            printf("%d\n",rows);
            if(rows == 0){
                printf("isvalid path:%s\n",tmpPath);
                return 0;   //表示路径不合法
            }
            //路径合法就得改id,
            id = atoi(row[0]);

        }

        substr = strtok(NULL,"/");
    }
    //printf("end of id: %d\n",id);
    return id;
}
